package com.bookbuf.android.permission.delegate;

import android.app.Activity;
import android.os.Build;
import android.support.annotation.NonNull;
import android.util.Log;

import com.bookbuf.android.permission.entity.PermEntityCompat;
import com.bookbuf.android.permission.inf.OnRequestPermissionsResultCallback;
import com.bookbuf.android.permission.inf.PermDelegateInf;
import com.bookbuf.android.permission.inf.PermDelegateInfImpl;
import com.bookbuf.android.permission.inf.PermDelegateInfImpl23;

import java.util.Arrays;

public class PermDelegateCompat {

	protected static final String TAG = "PermDelegateCompat";


	public static void onRequestPermissionsResult (int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
		Log.w (TAG, "onRequestPermissionsResult: +");
		Log.d (TAG, "onRequestPermissionsResult: requestCode = " + requestCode);
		Log.d (TAG, "onRequestPermissionsResult: permissions = " + Arrays.toString (permissions));
		Log.d (TAG, "onRequestPermissionsResult: grantResults = " + Arrays.toString (grantResults));

		getPermDelegateInfCompat ().parse (requestCode, permissions, grantResults);
		getPermDelegateInfCompat ().untrace (requestCode);
		Log.w (TAG, "onRequestPermissionsResult: -");
	}

	public static class Client {

		public static void register (Activity activity, OnRequestPermissionsResultCallback<PermEntityCompat> callback) {
			getPermDelegateInfCompat ().register (activity, callback);
		}

		public static void request (PermEntityCompat... permEntities) {
			getPermDelegateInfCompat ().trace (permEntities);
			getPermDelegateInfCompat ().request (permEntities);
		}

		public static void check (PermEntityCompat... permEntities) {
			getPermDelegateInfCompat ().check (permEntities);
		}

		public static void unregister (Activity activity, OnRequestPermissionsResultCallback<PermEntityCompat> callback) {
			getPermDelegateInfCompat ().unregister (activity, callback);
		}

		/**
		 * 若无权限  申请权限,并通过回调告知已有权限;
		 * 若有权限  通过回调告知已有权限;
		 */
		public static void requestIfNotAcquirePermission (PermEntityCompat... permissions) {
			boolean acquire = getPermDelegateInfCompat ().check (permissions);
			if (!acquire) {
				getPermDelegateInfCompat ().trace (permissions);
				getPermDelegateInfCompat ().request (permissions);
			}
		}
	}

	private static PermDelegateInf<PermEntityCompat> permDelegate;

	public static PermDelegateInf<PermEntityCompat> getPermDelegateInfCompat () {

		if (permDelegate != null) return permDelegate;
		synchronized (PermDelegateCompat.class) {
			if (permDelegate != null) return permDelegate;
			if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
				permDelegate = new PermDelegateInfImpl23 ();
			} else {
				permDelegate = new PermDelegateInfImpl ();
			}
		}
		return permDelegate;
	}

}
